package com.server.core.util;

import com.server.core.action.AbstractAction;
import com.server.core.anno.Controller;
import com.server.core.anno.HttpFilter;
import com.server.core.filter.AbstractFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Filter注册，查找类
 */
public class FilterUtil {

    private static  PackageScanUtil scanner = PackageScanUtil.getInstance();
    public static List<Class> classes = new ArrayList<>();
    //// 存储一个action to Map的数据结构
    public static Map<Class, AbstractFilter> actionMap = new HashMap<>();
    private static  Object lock = new Object();

    /**
     * @desc 通过class查找action
     * @param actionClass
     * @return
     */
    public static AbstractFilter FilterChainBuild(Class actionClass)  {
        System.out.println(actionClass.toString() + actionMap.get(actionClass) + actionMap);
          return  actionMap.get(actionClass);
    }

    /*
    包扫描，找到所有的action
    */
    public static  void  packageScan(String dir) {
        System.out.println("packageScan");
        classes = scanner.packageScan(dir, AbstractAction.class);
    }

    /*
    构建actionMap
     */
    public static void setActionMap() {
        System.out.println("正在扫描filter");
        int i = 0;
        classes.forEach(item -> {
            HttpFilter[] filters = (HttpFilter[]) item.getAnnotationsByType(HttpFilter.class);

            for (HttpFilter filter : filters) {
                AbstractFilter filter1 = null;
                try {
                    filter1 = (AbstractFilter) filter.filter().newInstance();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }

                if (actionMap.containsKey(item)) {
                    actionMap.get(item).next(filter1);
                } else {
                    actionMap.put(item, filter1);
                }
                System.out.println(item.getName() + filter);
            }
        });
    }
}
